/*
  * Mirante Tecnologia
  * Copyright 2010, Mirante Informatica LTDA, 
  * and individual contributors as indicated by the @authors tag
  *
  * This is free software; you can redistribute it and/or modify it
  * under the terms of the GNU Lesser General Public License as
  * published by the Free Software Foundation; either version 2.1 of
  * the License, or (at your option) any later version.
  *
  * This software is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with this software; if not, write to the Free
  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
  */
package com.miranteinfo.seam.jsf.converter;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.intercept.BypassInterceptors;
import org.jboss.seam.core.Interpolator;
import org.jboss.seam.core.ResourceBundle;

import com.miranteinfo.seam.facelets.util.input.InputDateTag;

/**
 * Converter de data.
 * 
 * @author lucas lins
 *
 */
@BypassInterceptors
@Name("com.miranteinfo.DateConverter")
@org.jboss.seam.annotations.faces.Converter
public class DateConverter implements Converter{

	public Object getAsObject(FacesContext context, UIComponent component, String value) {
		if(value == null || value.trim().length() < 1) return null;
		
		try{
			
			String pattern = InputDateTag.getPattern(component);
			if(value.length() != pattern.length()){
				throw new Exception();
			}
			
			SimpleDateFormat df = new SimpleDateFormat(pattern);
			df.setLenient(false);
			
			return df.parse(value);
			
		}catch (Exception e) {
			String label = (String)component.getAttributes().get("label");
			if(label != null && !label.trim().equals("")){
				throw new ConverterException(new FacesMessage(Interpolator.instance().interpolate(ResourceBundle.instance().getString("mirseam.converter.date_detail"),label)));
			}else{
				throw new ConverterException(new FacesMessage(ResourceBundle.instance().getString("mirseam.converter.date")));
			}
		}
	}

	public String getAsString(FacesContext context, UIComponent component, Object value) {
		if(value == null) return null;
		return new SimpleDateFormat(InputDateTag.getPattern(component)).format((Date) value);
	}
	
}
